package com.zzx.business.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzx.common.core.page.TableDataInfo;
import com.zzx.common.utils.PageUtils;
import com.zzx.business.domain.TbNodes;
import com.zzx.business.vo.TbNodesVo;
import com.zzx.business.mapper.TbNodesMapper;
import com.zzx.business.service.ITbNodesService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 项目节点Service业务层处理
 *
 * @author Zzx
 * @date 2025-05-23
 */
@Service
public class TbNodesServiceImpl extends ServiceImpl<TbNodesMapper, TbNodes> implements ITbNodesService {

    @Override
    public TableDataInfo<TbNodesVo> queryList(TbNodesVo entity) {
        return PageUtils.buildDataInfo(this.baseMapper.queryList(PageUtils.buildPage(), entity));
    }

    @Override
    public List<TbNodesVo> queryAll(TbNodesVo entity) {
        return this.baseMapper.queryList(entity);
    }

    @Override
    public TbNodesVo queryById(Long id) {
        return this.baseMapper.queryById(id);
    }

    @Transactional
    @Override
    public boolean saveNode(TbNodesVo entity) {
        this.save(entity);

        if(entity.getFrom() != null && entity.getFrom() != 0){
            TbNodes byId = this.getById(entity.getFrom());
            byId.setTo(entity.getId());
            this.updateById(byId);
        }

        if(entity.getTo() != null && entity.getTo() != 0){
            TbNodes byId = this.getById(entity.getTo());
            byId.setFrom(entity.getId());
            this.updateById(byId);
        }

        return true;
    }

    @Transactional
    @Override
    public boolean removeByIds(List<Long> ids) {
        if(!ids.isEmpty()){
            for (Long id : ids) {
                TbNodes byId = this.getById(id);
                Long toId = byId.getTo();
                Long fromId = byId.getFrom();
                if(toId != 0l){
                    TbNodes byId1 = this.getById(toId);
                    byId1.setFrom(fromId);
                    this.updateById(byId1);
                }
                if(fromId != 0l){
                    TbNodes byId1 = this.getById(fromId);
                    byId1.setTo(toId);
                    this.updateById(byId1);
                }
                this.removeById(id);
            }
        }
        return true;
    }
}
